# g5_ok.py  ✅ gradio 5.34.2 验证 - 方法3（最简单可靠）
import gradio as gr
import time

# 图片路径配置
ASSET_PATH = "./src/assets"
USER_AVATAR = f"{ASSET_PATH}/user_avatar.jpeg"
BOT_AVATAR = f"{ASSET_PATH}/bot_avatar.png"
BANNER_IMAGE = f"{ASSET_PATH}/logo.jpeg"

QUESTIONS = [
    "我的投资组合中科技股占比是多少？",
    "今天上证指数的表现如何？",
    "根据当前市场情况，我应该如何调整投资组合以应对可能的经济衰退？",
    "考虑到我的退休目标，请评估我当前的投资策略并提供优化建议。",
    "请解释一下什么是ETF？",
    "我想为子女准备教育金，请帮我设计一个10年期的投资计划。",
]

# 初始化历史对话为空
initial_history = ["暂无历史对话..."]

def bot(history, prompt, current_history):
    """处理用户消息并生成回复"""
     
    # 模拟思考过程
    history.append([prompt, None])
    yield history, current_history, ""
    time.sleep(1)
    
    # 模拟回复
    bot_responses = {
        "我的投资组合中科技股占比是多少？": "根据您的投资组合分析，科技股占比约为35%，处于合理区间。建议保持当前配置。",
        "今天上证指数的表现如何？": "今日上证指数上涨1.2%，收于3250点。科技板块表现强劲，金融板块相对平稳。",
        "根据当前市场情况，我应该如何调整投资组合以应对可能的经济衰退？": "建议适当增加防御性资产配置，如消费必需品和医疗板块，同时减少周期性行业 exposure。",
        "考虑到我的退休目标，请评估我当前的投资策略并提供优化建议。": "您当前的投资策略较为激进，建议增加债券和稳定收益产品比例，确保退休资金安全。",
        "请解释一下什么是ETF？": "ETF是交易所交易基金，它结合了股票和基金的优点，可以在交易所实时交易，具有分散风险和成本低的优势。",
        "我想为子女准备教育金，请帮我设计一个10年期的投资计划。": "建议采用渐进式投资策略：前5年偏重成长型基金，后5年逐步转向稳健型产品，确保教育金安全增值。"
    }
    
    bot_response = bot_responses.get(prompt, f"已收到您的问题：{prompt}。我将为您提供专业的保险和投资建议。")
    
    history[-1][1] = bot_response
    
    # 生成对话总结并添加到历史对话
    conversation_summary = generate_conversation_summary(prompt, bot_response)
    if current_history == ["暂无历史对话..."]:
        updated_history = [conversation_summary]
    else:
        updated_history = current_history + [conversation_summary]
    
    yield history, updated_history, ""

def generate_conversation_summary(user_question, bot_response):
    """生成对话总结"""
    # 简化的总结逻辑 - 实际应用中可以使用更复杂的NLP模型
    if "科技股" in user_question:
        return "投资组合分析 - 科技股占比咨询"
    elif "上证指数" in user_question:
        return "市场行情咨询 - 上证指数表现"
    elif "经济衰退" in user_question or "调整投资" in user_question:
        return "投资策略调整 - 应对经济波动"
    elif "退休" in user_question:
        return "退休规划 - 投资策略评估"
    elif "ETF" in user_question:
        return "产品知识 - ETF概念解释"
    elif "教育金" in user_question:
        return "教育规划 - 10年期投资方案"
    else:
        # 截取前20个字符作为标题
        summary = user_question[:20] + "..." if len(user_question) > 20 else user_question
        return f"保险咨询 - {summary}"

def load_history_conversation(conversation_title, chat_history, current_history):
    """加载历史对话到聊天区域"""
    if conversation_title == "暂无历史对话...":
        return chat_history, current_history
    
    # 模拟历史对话内容
    history_content = {
        "投资组合分析 - 科技股占比咨询": [
            [USER_AVATAR, "我的投资组合中科技股占比是多少？"],
            [BOT_AVATAR, "根据您的投资组合分析，科技股占比约为35%，处于合理区间。建议保持当前配置。"]
        ],
        "市场行情咨询 - 上证指数表现": [
            [USER_AVATAR, "今天上证指数的表现如何？"],
            [BOT_AVATAR, "今日上证指数上涨1.2%，收于3250点。科技板块表现强劲，金融板块相对平稳。"]
        ],
        "投资策略调整 - 应对经济波动": [
            [USER_AVATAR, "根据当前市场情况，我应该如何调整投资组合以应对可能的经济衰退？"],
            [BOT_AVATAR, "建议适当增加防御性资产配置，如消费必需品和医疗板块，同时减少周期性行业 exposure。"]
        ]
    }
    
    simulated_history = history_content.get(conversation_title, [
        [USER_AVATAR, f"关于{conversation_title}的咨询"],
        [BOT_AVATAR, f"这是关于{conversation_title}的历史对话内容..."]
    ])
    
    return simulated_history, current_history

def clear_all_chat(chat_history, current_history):
    """清空所有聊天记录和历史对话"""
    return [], ["暂无历史对话..."]

with gr.Blocks(title="保险助手") as demo:
    
    # 状态变量
    current_history = gr.State(value=initial_history)
    
    with gr.Row():
        # 左侧栏 - 包含banner和标题
        with gr.Column(scale=1, elem_classes="left-sidebar"):
            # 左侧栏内容容器
            with gr.Column(elem_classes="sidebar-content-container"):
                # Banner图片
                gr.Image(
                    BANNER_IMAGE, 
                    show_label=False, 
                    elem_classes="sidebar-banner"
                )
                
                # 标题区域 - 标题居中，副标题左对齐
                with gr.Column(elem_classes="title-section"):
                    gr.Markdown(
                        "## 中国平安",
                        elem_classes="main-title"
                    )
                    gr.Markdown(
                        "### 保费·银行·投资",
                        elem_classes="sub-title"
                    )
                
                # 助手信息区域
                with gr.Column(elem_classes="assistant-section"):
                    gr.Markdown(
                        "### 保险助手",
                        elem_classes="assistant-title"
                    )
                    gr.Markdown(
                        "一个用于保险的助手，能够处理保险相关的问题。优先使用内部保险知识库。",
                        elem_classes="assistant-description"
                    )
                    
                    # 历史对话区域
                    gr.Markdown("### 历史对话", elem_classes="history-title")
                    
                    # 动态历史对话按钮
                    history_buttons = []
                    for i in range(5):  # 最多显示5个历史对话
                        btn = gr.Button(
                            "暂无历史对话...",
                            size="sm",
                            variant="secondary", 
                            min_width=200,
                            elem_classes="history-btn",
                            visible=False  # 初始隐藏
                        )
                        history_buttons.append(btn)
                    
                    # 推荐对话区域
                    gr.Markdown("###推荐对话", elem_classes="recommend-title")
                    
                    # 创建6个推荐问题按钮
                    question_buttons = []
                    for i, question in enumerate(QUESTIONS):
                        btn = gr.Button(
                            question,
                            size="sm",
                            variant="secondary",
                            min_width=200,
                            elem_classes="recommend-btn"
                        )
                        question_buttons.append(btn)
                    
                    # 清空对话按钮
                    clear_btn = gr.Button(
                        "🗑️ 清空所有对话",
                        size="sm",
                        variant="secondary",
                        elem_classes="clear-btn"
                    )
                
        # 右侧聊天区域
        with gr.Column(scale=3):
            chat = gr.Chatbot(
                height=800,
                avatar_images=(USER_AVATAR, BOT_AVATAR)
            )
            
            # 输入区域 - 使用Row布局让输入框和按钮在同一行
            with gr.Row(elem_classes="input-row"):
                inp = gr.Textbox(
                    show_label=False, 
                    placeholder="输入您的问题…",
                    scale=5,  # 输入框占据更多空间
                    elem_classes="input-textbox"
                )
                with gr.Column(scale=1, min_width=70, elem_classes="button-group"):
                    with gr.Row(elem_classes="button-row"):
                        # 发送按钮 - 使用elem_classes设置样式
                        send_btn = gr.Button(
                            "发送", 
                            variant="primary",
                            size="sm",
                            min_width=35,
                            elem_classes="send-btn"
                        )
                        clear_chat_btn = gr.Button(
                            "清空", 
                            variant="secondary",
                            size="sm", 
                            min_width=35,
                            elem_classes="clear-chat-btn"
                        )

    # 添加自定义CSS样式
    demo.css = """
    /* 整体布局 */
    .gradio-container {
        height: 100vh !important;
        max-width: 100% !important;
    }
    
    /* 主行布局 */
    .gradio-row {
        height: 100vh !important;
    }
    
    /* 左侧栏样式 */
    .left-sidebar {
        background: white !important;
        border-right: 1px solid #e0e0e0 !important;
        height: 100vh !important;
        padding: 0 !important;
        overflow: hidden !important;
    }
    
    /* 左侧栏内容容器 - 支持滚动 */
    .sidebar-content-container {
        height: 100vh !important;
        overflow-y: auto !important;
        padding-bottom: 20px !important;
    }
    
    /* 隐藏滚动条 */
    .sidebar-content-container::-webkit-scrollbar {
        width: 4px;
    }
    .sidebar-content-container::-webkit-scrollbar-thumb {
        background: #ddd;
        border-radius: 2px;
    }
    
    /* 侧边栏banner样式 */
    .sidebar-banner {
        width: 100% !important;
        height: 200px !important;
        object-fit: cover !important;
        margin-bottom: 0 !important;
    }
    
    /* 标题区域 */
    .title-section {
        padding: 20px !important;
        padding-bottom: 0 !important;
        text-align: center !important;
    }
    
    /* 主标题居中 */
    .main-title {
        color: #333 !important;
        font-weight: bold !important;
        margin-bottom: 8px !important;
        text-align: center !important;
    }
    
    /* 副标题左对齐 */
    .sub-title {
        color: #666 !important;
        font-weight: normal !important;
        margin-bottom: 0 !important;
        text-align: left !important;
        font-size: 16px !important;
    }
    
    /* 助手信息区域 */
    .assistant-section {
        padding: 20px !important;
        padding-top: 10px !important;
    }
    
    /* 助手标题样式 */
    .assistant-title {
        color: #1890ff !important;
        font-weight: bold !important;
        margin-bottom: 10px !important;
        text-align: left !important;
    }
    
    /* 助手描述样式 */
    .assistant-description {
        color: #666 !important;
        font-size: 14px !important;
        line-height: 1.5 !important;
        margin-bottom: 20px !important;
        text-align: left !important;
    }
    
    /* 历史对话标题 */
    .history-title {
        color: #333 !important;
        font-weight: bold !important;
        margin-bottom: 15px !important;
        text-align: left !important;
        border-bottom: 2px solid #52c41a !important;
        padding-bottom: 8px !important;
    }
    
    /* 历史对话按钮样式 */
    .history-btn {
        background: transparent !important;
        border: none !important;
        box-shadow: none !important;
        color: #666 !important;
        text-align: left !important;
        padding: 8px 12px !important;
        margin: 3px 0 !important;
        border-radius: 6px !important;
        font-size: 13px !important;
        line-height: 1.4 !important;
        width: 100% !important;
        justify-content: flex-start !important;
    }
    .history-btn:hover {
        background: #f6ffed !important;
        color: #52c41a !important;
        text-decoration: none !important;
        border-left: 3px solid #52c41a !important;
    }
    
    /* 推荐对话标题 */
    .recommend-title {
        color: #333 !important;
        font-weight: bold !important;
        margin-bottom: 15px !important;
        text-align: left !important;
        border-bottom: 2px solid #1890ff !important;
        padding-bottom: 8px !important;
        margin-top: 20px !important;
    }
    
    /* 推荐按钮样式 */
    .recommend-btn {
        background: transparent !important;
        border: none !important;
        box-shadow: none !important;
        color: #333 !important;
        text-align: left !important;
        padding: 10px 12px !important;
        margin: 4px 0 !important;
        border-radius: 6px !important;
        font-size: 14px !important;
        line-height: 1.4 !important;
        width: 100% !important;
        justify-content: flex-start !important;
    }
    .recommend-btn:hover {
        background: #f0f7ff !important;
        color: #1890ff !important;
        text-decoration: none !important;
        border-left: 3px solid #1890ff !important;
    }
    
    /* 清空按钮样式 */
    .clear-btn {
        background: transparent !important;
        border: 1px solid #ff4d4f !important;
        color: #ff4d4f !important;
        text-align: center !important;
        padding: 8px 12px !important;
        margin: 10px 0 !important;
        border-radius: 6px !important;
        font-size: 13px !important;
        width: 100% !important;
    }
    .clear-btn:hover {
        background: #fff2f0 !important;
        color: #ff4d4f !important;
    }
    
    /* 输入行样式 */
    .input-row {
        align-items: center !important;
        gap: 10px !important;
        width: 100% !important;
    }
    
    /* 输入框样式 */
    .input-textbox {
        flex: 1 !important;
        min-width: 200px !important;
    }
    
    /* 按钮组样式 */
    .button-group {
        display: flex !important;
        flex-direction: row !important;
        gap: 8px !important;
        justify-content: flex-end !important;
        min-width: 160px !important;
    }
    
    /* 发送按钮样式 */
    .send-btn {
        min-width: 70px !important;
        height: 40px !important;
    }
    
    /* 清空按钮样式 */
    .clear-chat-btn {
        min-width: 70px !important;
        height: 40px !important;
    }
    
    /* 调整头像大小 */
    .gradio-chatbot .avatar {
        width: 32px !important;
        height: 32px !important;
        border-radius: 50% !important;
    }
    
    /* 右侧聊天区域样式 */
    .gradio-row > .gradio-column:last-child {
        padding: 20px !important;
        height: 100vh !important;
        display: flex !important;
        flex-direction: column !important;
    }
    
    /* 聊天区域自适应高度 */
    .gradio-chatbot {
        flex: 1 !important;
    }
    """

    def update_history_buttons(history_list):
        """更新历史对话按钮的显示"""
        updates = []
        for i in range(5):
            if i < len(history_list):
                updates.append(gr.update(value=history_list[i], visible=True))
            else:
                updates.append(gr.update(visible=False))
        return updates

    # 初始化历史对话按钮
    demo.load(
        fn=update_history_buttons,
        inputs=[current_history],
        outputs=history_buttons
    )

    # 为历史对话按钮绑定事件
    for btn in history_buttons:
        btn.click(
            fn=load_history_conversation,
            inputs=[btn, chat, current_history],
            outputs=[chat, current_history]
        )

    # 为每个推荐问题按钮绑定事件
    for btn in question_buttons:
        btn.click(
            fn=lambda q=btn.value: q,
            outputs=[inp]
        ).then(
            lambda: None,
            None,
            None
        ).then(
            fn=bot,
            inputs=[chat, inp, current_history],
            outputs=[chat, current_history, inp]
        ).then(
            fn=update_history_buttons,
            inputs=[current_history],
            outputs=history_buttons
        )

    # 原有的发送方式
    inp.submit(
        fn=bot,
        inputs=[chat, inp, current_history],
        outputs=[chat, current_history, inp]
    ).then(
        fn=update_history_buttons,
        inputs=[current_history],
        outputs=history_buttons
    )
    
    send_btn.click(
        fn=bot,
        inputs=[chat, inp, current_history],
        outputs=[chat, current_history, inp]
    ).then(
        fn=update_history_buttons,
        inputs=[current_history],
        outputs=history_buttons
    )

    # 清空对话按钮
    clear_btn.click(
        fn=clear_all_chat,
        inputs=[chat, current_history],
        outputs=[chat, current_history]
    ).then(
        fn=update_history_buttons,
        inputs=[current_history],
        outputs=history_buttons
    )
    
    clear_chat_btn.click(
        fn=lambda: [],
        outputs=[chat]
    )

demo.launch()